package com.dingwen.treasure.web.excption.handler.impl;

import com.dingwen.treasure.base.constant.ExceptionConstant;
import com.dingwen.treasure.base.exception.BaseExceptionHandler;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.base.pojo.vo.ResultGenerator;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 　MethodArgumentNotValidExceptionHandlerImpl：方法参数校验异常处理
 * 　@author dingwen
 * 　@date 2022/5/14$
 */
@Component("org.springframework.web.bind.MethodArgumentNotValidException")
public class MethodArgumentNotValidExceptionHandlerImpl extends BaseExceptionHandler<List<String>> {
    /**
     * 根据异常构建统一返回结果
     *
     * @param exception 异常
     * @return result
     */
    @Override
    public Result<List<String>> buildResultByException(Exception exception) {
        MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
        // TODO 为什么直接收集为Map会抛出异常
        List<String> errInfo = methodArgumentNotValidException.getBindingResult().getFieldErrors()
                .parallelStream()
                .map(ele -> ele.getField().concat(":").concat(Objects.requireNonNull(ele.getDefaultMessage())))
                .collect(Collectors.toList());
        return ResultGenerator.genFailureResult(ExceptionConstant.METHOD_PARAM_EX, HttpStatus.BAD_REQUEST.value(), errInfo);
    }
}
